package com.demo.testversion1

import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.withTimeoutOrNull
import org.junit.Test

/**
 * Created by zhangyuncai on 2025/1/21.
 * 描述：
 */
class CoroutineTest04 {

    @Test
    fun `test deal with timeout`(): Unit = runBlocking {
        /*
        Timed out waiting for 1300 ms
kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 1300 ms
         */
        withTimeout(1300) {
            repeat(1000) { i ->
                println("sleep:${i}")
                delay(500L)
            }
        }
    }

    @Test
    fun `test deal with timeout return null`(): Unit = runBlocking {
        /*
        Timed out waiting for 1300 ms
kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 1300 ms
         */
        val result = withTimeoutOrNull(1300) {
            repeat(1000) { i ->
                println("sleep:${i}")
                delay(500L)
                "Done"//正常完成返回"Done",否则返回null
            }
        } ?: "Jack"//如果返回null则实际返回"Jack"
        println("result:${result}")
    }

}